const sleep = require('../common/sleep');
const sharedResourcesBuilder = require('../shared-resources-builder');
const ec2 = require("./aws/ec2-restApi");
const d = {};

d.reassignAddressToInstance = async (instanceName, vpcId, subnetId) => {
    console.log(`getting ec2 instance...`);
    const ec2Instances = await sharedResourcesBuilder.findEC2InstancesByName(instanceName, vpcId, subnetId);
    if (ec2Instances.length <= 0) {
        throw Error(`no instance found by name ${instanceName}`);
    }
    const instanceId = ec2Instances[0].InstanceId;
    console.log(`ec2 instanceId: ${instanceId}`);
    console.log(`allocating address...`);
    const allocateAddressResp = await ec2.allocateAddress({});
    const allocationId = allocateAddressResp.AllocationId;
    const publicIp = allocateAddressResp.PublicIp;
    console.log(`public ip: ${publicIp}`);
    console.log(`associating address...`);
    const associateAddressResp = await ec2.associateAddress({
        AllocationId: allocationId,
        InstanceId: instanceId
    });
    console.log(`associationId: ${associateAddressResp.AssociationId}`);
    console.log(`releasing unused addresses...`);
    const data = await ec2.describeAddresses();
    for (const address of data.Addresses){
        console.log(`checking address ${address.PublicIp}...`);
        if (!address.AssociationId) {
            const result = await ec2.releaseAddress({AllocationId: address.AllocationId})
            console.log(`released address ${address.PublicIp}`);
        }
    }
    console.log("done");
};

module.exports = d;

if (require.main === module) {
    (async () => {
        await d.reassignAddressToInstance("v2ray", "", "");

    })();
}